<?php

namespace Application\model;

use Cola\Exception;
use Cola\Model;

class GiftModel extends Model
{
    public function getGiftCodeInfoByCode($code)
    {
        $sql = "select * from `gm_gift_code` where `code` = '$code'";
        return $this->db->row($sql);
    }

    public function getGiftInfoById($id)
    {
        $sql = "select * from `gm_gift` where `id` = $id";
        return $this->db->row($sql);
    }
    public function getGiftCodeConfigInfoById($id)
    {
        $sql = "select * from `gm_gift_code_config` where `id` = $id";
        return $this->db->row($sql);
    }

    public function getGiftCodeLogInfoByActorId($actorId)
    {
        $sql = "select * from `gm_gift_code_log` where `actor_id` = $actorId order by create_dt desc";
        return $this->db->sql($sql);
    }

    public function insertGiftCodeLog($row)
    {
        return $this->db->insert( $row, "gm_gift_code_log");
    }

    public function delGiftCodeLog($row)
    {
        return $this->db->delete( $row, "gm_gift_code_log");
    }

    public function updateGift($row): bool
    {
        $this->db->beginTransaction();
        try {
            // 更新code表 $fields, $value, $where = [], $table
            $r1 = $this->db->setIncDec('used_times', 1, ['code' => $row['code']], 'gm_gift_code');
            $r2 = $this->db->update(['status'=>1], "code='{$row['code']}'", 'gm_gift_code');
            // 更新config表
            $r3 = $this->db->setIncDec('used_num', 1, ['id' => $row['config_id']], 'gm_gift_code_config');
            // 更新gift表
            $r4 = $this->db->setIncDec('used_num', 1, ['id' => $row['gift_id']], 'gm_gift');

            $this->db->commit();
        } catch (Exception $e) {
            $this->db->rollback();
            return false;
        }
        return true;

    }

}